package com.cjk.foundation.builder;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.springframework.beans.BeanUtils;

public abstract class AbstractBeanBuilder<T> implements BeanBuilder<T> {

	private final T instance;

	@SuppressWarnings("unchecked")
	public AbstractBeanBuilder() {
		Class<?> clazz = getClass();
		ParameterizedType genericSuperclass = (ParameterizedType) clazz.getGenericSuperclass();
		Type genernicArgs0 = genericSuperclass.getActualTypeArguments()[0];
		if ((genernicArgs0 instanceof Class)) {
			Class<T> beanClass = (Class<T>) genernicArgs0;
			this.instance = BeanUtils.instantiate(beanClass);
		} else if ((genernicArgs0 instanceof ParameterizedType)) {
			ParameterizedType typ2 = (ParameterizedType) genernicArgs0;
			Type rawType = typ2.getRawType();
			Class<T> beanClass = (Class<T>) rawType;
			this.instance = BeanUtils.instantiate(beanClass);
		} else {
			throw new UnsupportedOperationException("不支持的类型, genernicArgs0=" + genernicArgs0);
		}
	}

	public T build() {
		return this.instance;
	}

	protected T getInstance() {
		return this.instance;
	}
}
